<template>
  <div class="space-y-6">
    <!-- 日期筛选器 -->
    <n-card size="small" :bordered="false" class="filter-card">
      <div class="flex items-center gap-4">
        <span class="text-sm font-medium text-gray-700">活动日期筛选：</span>
        <n-date-picker
          v-model:formatted-value="startDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="开始日期"
          clearable
          @update:value="handleStartDateChange"
        />
        <span class="text-gray-500">至</span>
        <n-date-picker
          v-model:formatted-value="endDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="结束日期"
          clearable
          @update:value="handleEndDateChange"
        />
        <n-button size="small" type="primary" @click="handleDateFilter">
          筛选
        </n-button>
        <n-button size="small" @click="clearDateFilter">
          清除筛选
        </n-button>
      </div>
    </n-card>

    <!-- 筛选结果统计 -->
    <n-card v-if="isDateFilterActive" size="small" :bordered="false" class="filter-stats-card">
      <div class="flex items-center justify-between">
        <span class="text-sm text-gray-600">
          筛选条件：{{ formatDate(startDate) }} 至 {{ formatDate(endDate) }}
        </span>
        <n-tag type="info" size="small">
          找到 {{ filteredActivities.length }} 个活动
        </n-tag>
      </div>
    </n-card>

    <!-- 活动时间轴 -->
    <div v-if="filteredActivities && filteredActivities.length > 0" class="relative pl-5 border-l-2 border-slate-200">
      <n-card
        v-for="activity in filteredActivities"
        :key="activity.activityId"
        class="mb-6 activity-card"
        hoverable
      >
        <!-- 时间轴上的圆点和图标 -->
        <div class="absolute -left-[11px] top-6 w-5 h-5 bg-white border-2 border-blue-500 rounded-full flex items-center justify-center">
          <n-icon :component="getIconForActivityType(activity.activityType)" class="text-blue-500" size="12" />
        </div>

        <div class="flex flex-col md:flex-row md:justify-between md:items-start">
          <!-- 左侧：活动信息 -->
          <div class="flex-grow">
            <h4 class="text-md font-semibold text-gray-800 mb-1">{{ activity.activityName || '未命名活动' }}</h4>
            <div class="flex items-center gap-4 text-sm text-gray-500 mb-3">
              <n-tag :bordered="false" size="small" round>
                <template #icon><n-icon :component="CalendarIcon" /></template>
                {{ formatDate(activity.activityDate) }}
              </n-tag>
              <n-tag :bordered="false" size="small" round :type="getTagTypeForActivity(activity.activityType)">
                {{ activity.activityType || '常规活动' }}
              </n-tag>
              <n-tag :bordered="false" size="small" round type="success">
                 <template #icon><n-icon :component="PeopleIcon" /></template>
                {{ (activity.participants || []).length }} 人参与
              </n-tag>
            </div>
            <p class="text-sm text-gray-600 pr-4">{{ activity.activityContent || '暂无详细内容。' }}</p>
          </div>

          <!-- 右侧：操作按钮 -->
          <div class="flex-shrink-0 mt-4 md:mt-0">
            <n-space>
              <n-button size="small" secondary @click="emit('edit-activity', activity)">
                <template #icon><n-icon :component="EditIcon"/></template>
                编辑
              </n-button>
              <n-button size="small" type="error" ghost @click="emit('delete-activity', activity)">
                <template #icon><n-icon :component="DeleteIcon"/></template>
                删除
              </n-button>
            </n-space>
          </div>
        </div>
      </n-card>
    </div>

    <!-- 空状态 -->
    <div v-if="!filteredActivities || filteredActivities.length === 0" class="text-center py-12 text-gray-500">
      <n-icon size="48" class="mb-4 text-gray-300" :component="EmptyCalendarIcon" />
      <p class="text-base">暂无任何活动记录</p>
      <p class="text-sm mt-2">您可以点击右上方的 "新增活动" 按钮来记录第一次活动</p>
    </div>
  </div>
</template>

<script setup>
import { NCard, NButton, NIcon, NTag, NSpace, NDatePicker } from 'naive-ui';
import { computed, ref } from 'vue';
import {
  CalendarOutline as CalendarIcon,
  PeopleOutline as PeopleIcon,
  CreateOutline as EditIcon,
  TrashOutline as DeleteIcon,
  CalendarNumberOutline as EmptyCalendarIcon,
  BulbOutline as BulbIcon, // 主题党日
  ChatbubblesOutline as ChatIcon, // 组织生活会
  HeartOutline as HeartIcon, // 志愿服务
  SchoolOutline as SchoolIcon, // 理论学习
} from '@vicons/ionicons5';

const props = defineProps({
  activities: { type: Array, default: () => [] }
});

// 定义清晰的 emit 事件
const emit = defineEmits(['edit-activity', 'delete-activity']);

// 日期筛选相关状态
const startDate = ref(null)
const endDate = ref(null)
const isDateFilterActive = ref(false)

// --- 计算属性 ---
const sortedActivities = computed(() => {
  // 创建一个副本进行排序，避免直接修改 props
  return [...props.activities].sort((a, b) => new Date(b.activityDate) - new Date(a.activityDate));
});

const filteredActivities = computed(() => {
  // 如果没有激活日期筛选，返回所有排序后的活动
  if (!isDateFilterActive.value) {
    return sortedActivities.value;
  }
  
  // 应用日期筛选
  return sortedActivities.value.filter(activity => {
    const activityDate = new Date(activity.activityDate);
    const start = startDate.value ? new Date(startDate.value) : null;
    const end = endDate.value ? new Date(endDate.value) : null;
    
    // 如果有开始日期，活动日期必须晚于或等于开始日期
    if (start && activityDate < start) {
      return false;
    }
    
    // 如果有结束日期，活动日期必须早于或等于结束日期
    if (end && activityDate > end) {
      return false;
    }
    
    return true;
  });
});

// --- 工具函数 ---
const formatDate = (dateStr) => {
  if (!dateStr) return '未知日期';
  try {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
  } catch (e) {
    return dateStr;
  }
};

const getIconForActivityType = (type) => {
  const iconMap = {
    '主题党日': BulbIcon,
    '组织生活会': ChatIcon,
    '志愿服务': HeartIcon,
    '理论学习': SchoolIcon,
  };
  return iconMap[type] || CalendarIcon;
};

const getTagTypeForActivity = (type) => {
  const typeMap = {
    '主题党日': 'warning',
    '组织生活会': 'info',
    '志愿服务': 'error',
    '理论学习': 'success',
  };
  return typeMap[type] || 'default';
};

// 日期筛选功能
const handleStartDateChange = (value) => {
  startDate.value = value;
}

const handleEndDateChange = (value) => {
  endDate.value = value;
}

const handleDateFilter = () => {
  if (startDate.value || endDate.value) {
    isDateFilterActive.value = true;
  }
}

const clearDateFilter = () => {
  startDate.value = null;
  endDate.value = null;
  isDateFilterActive.value = false;
}
</script>

<style scoped>
.activity-card {
  transition: all 0.3s ease;
}
.activity-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}
.filter-card {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
}
.filter-stats-card {
  background-color: #e6f7ff;
  border-left: 4px solid #1890ff;
}
</style>
